package net.easyjava.framework.web.elastiesearch;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by wenxiaoning on 16/6/18.
 */
@Deprecated
public class ESearchUtils {


    public static IndexResponse createIndex(String indexName,String type,String sourceJson){
        return createIndex(indexName,type,null,sourceJson);
    }
    /**
     * 创建索引
     * @param indexName 索引名称
     * @param type 索引类型
     * @param id 如果为null就自动生成id 不能为空字符串
     * @param sourceJson 数据json格式
     * @return
     */
    public static IndexResponse createIndex(String indexName,String type,String id,String sourceJson){
        if(id != null && "".equalsIgnoreCase(id)){
            throw new ESearchException("id can't be ''");
        }
        Client client = null;
        try {
            client = ESClient.getClient();
            IndexResponse response = client.prepareIndex(indexName, type, id)
                    .setSource(sourceJson)
                    .get();
            return response;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(client != null){
                ESClient.closeClient();
            }
        }
        return null;
    }


    /**
     * 删除索引
     * @param indexName
     * @param type
     * @param id
     * @return
     */
    public static DeleteResponse deleteIndex(String indexName,String type,String id){
        Client client = null;
        try {
            client = ESClient.getClient();
            DeleteResponse deleteResponse = client.prepareDelete(indexName, type, id).get();
            return deleteResponse;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(client != null){
                ESClient.closeClient();
            }
        }
        return null;
    }

    /**
     * 读取索引
     * @param indexName
     * @param type
     * @param id
     * @return
     */
    public static GetResponse getIndex(String indexName,String type,String id){
        Client client = null;
        try {
            client = ESClient.getClient();
            GetResponse response = client.prepareGet(indexName, type, id).get();
            return response;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(client != null){
                ESClient.closeClient();
            }
        }
        return null;
    }

    public static BulkResponse bulkCreateIndex(List<IndexRequest> indexRequests){
        Client client = null;
        try {
            client = ESClient.getClient();
            BulkRequestBuilder bulkRequest = client.prepareBulk();
            for(IndexRequest indexRequest:indexRequests){
                bulkRequest.add(indexRequest);
            }
            return bulkRequest.get();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ESClient.closeClient();
        }
        return null;
    }

    /**
     * 批量操作
     * @param objects
     * @return
     */
    public static BulkResponse bulkIndex(Object... objects){
        Client client = null;
        try {
            client = ESClient.getClient();
            BulkRequestBuilder bulkRequest = client.prepareBulk();
            for(Object obj:objects){
                if(obj instanceof IndexRequest){
                    bulkRequest.add((IndexRequest)obj);
                }else if(obj instanceof DeleteRequest){
                    bulkRequest.add((DeleteRequest)obj);
                }else if(obj instanceof UpdateRequest){
                    bulkRequest.add((UpdateRequest)obj);
                }else{
                    throw new ESearchException("objects must include IndexRequest , DeleteRequest" +
                            "or UpdateRequest");
                }
            }
            return bulkRequest.get();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ESClient.closeClient();
        }
        return null;
    }

    /**
     * 批量生成索引
     * @param indexName
     * @param type
     * @param sources
     * @return
     */
    public static BulkResponse bulkCreateIndex(String indexName,String type,String... sources){
        List<String> list = Arrays.asList(sources);
        return bulkCreateIndex(indexName, type, list);
    }

    public static BulkResponse bulkCreateIndex(String indexName,String type,List<String> sources){
        Client client = null;
        try {
            client = ESClient.getClient();
            BulkRequestBuilder bulkRequest = client.prepareBulk();
            for(String source:sources){
                bulkRequest.add(client.prepareIndex(indexName,type).setSource(source));
            }
            return bulkRequest.get();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ESClient.closeClient();
        }
        return null;
    }


    public static SearchResponse search(String indexName,String type,String query){
        Client client = null;
        try {
            client = ESClient.getClient();
            SearchResponse searchResponse = client.prepareSearch(indexName)
                    .setTypes(type)
                    .setSize(20)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setQuery(QueryBuilders.queryStringQuery(query))                 // Query
//                .setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18))     // Filter
//                .setFrom(0).setSize(60).setExplain(true)
                    .execute()
                    .actionGet();
            return searchResponse;
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ESClient.closeClient();
        }
        return null;

    }

    public static void main(String[] args) {
        String json = "{" +
                "\"user\":\"kimchy trying\"," +
                "\"postDate\":\"2013-01-30\"," +
                "\"message\":\"trying out Elasticsearch\"" +
                "}";


        IndexResponse  index =  ESearchUtils.createIndex("index_5", "tweet", null, json);
//        index =  ESearchUtils.createIndex("index_3", "tweet", null, json);
        List<String> list = new ArrayList<String>();
        for(int i=0;i<10;i++){
//            final String source = json;
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    ESearchUtils.createIndex("index_3", "tweet", null, source);
//                }
//            }).run();
        }
        long begin = System.currentTimeMillis();
//        BulkResponse bulkResponse = ESearchUtils.bulkCreateIndex("index_8", "tweet", list);
        long end = System.currentTimeMillis();
//        System.out.println("bulkResponse = " + bulkResponse.getTook());
//        System.out.println("(end-begin) = " + (end - begin));




//        System.out.println("bulkResponse.hasFailures() = " + bulkResponse.hasFailures());
//        System.out.println("index.isCreated() = " + index.isCreated());
//        System.out.println("json = " + index.getId());
    }
}
